<?php

namespace App\Service\Office;

use App\DataStore\RedisGeneral;
use App\Service\ServiceGeneral;
use Ramsey\Uuid\Uuid;
use Vtiful\Kernel\Excel;

class ExcelService extends ServiceGeneral
{

//ExcelService::getInc()->import(BASE_PATH,'test.xlsx');
//ExcelService::getInc()->export(BASE_PATH,'xxxx.xlsx',jsonDecode(RedisGeneral::getInc()->getImport('1915b6c36be18cbe5731198ce585b7a3')),[
//'描述',
//'地址'
//]);

    public function import($path,$file_name){
        $ex_config = [
            'path' => $path
        ];
        $excel = new Excel($ex_config);

        if (file_exists($path.DIRECTORY_SEPARATOR.$file_name)) {
            $md5 = md5_file($path.DIRECTORY_SEPARATOR.$file_name);
        } else {
            apiError("文件导入失败!");
        }

        $sheetList = $excel->openFile($file_name)->sheetList();
        //循环读取工作表
        $data = [];
        foreach ($sheetList as $sheetName) {
            //读取工作表内容
            $excel->openSheet($sheetName)->setSkipRows(0);
            //游标模式读取数据
            while (($row = $excel->nextRow()) !== NULL) {
                $data[] = $row;
            }
        }
        // 存入Redis
        RedisGeneral::getInc()->setImport($md5,$data);
        return $md5;
    }

    public function export($path,$file_name,$data,$header = [],$sheet = 'sheet1'){
        $ex_config = [
            'path' => $path
        ];
        $excel = new Excel($ex_config);
        return $excel->fileName($file_name, $sheet)
            ->header($header)
            ->data($data)
            ->output();
    }

}